package com.lczyfz.istep.modules.mobile.utils;

/**
 * Created by hpp on 2017/6/5.
 */

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
import com.lczyfz.istep.common.utils.StringUtils;

import java.io.*;

/**
 * 远程执行linux的shell script
 *
 * @author Ickes
 * @since V0.1
 */
public class RemoteExecuteCommand {
    //字符编码默认是utf-8
    private static String DEFAULTCHART = "UTF-8";
    private static Connection conn;
    private String ip;
    private String userName;
    private String userPwd;

    public RemoteExecuteCommand(String ip, String userName, String userPwd) {
        this.ip = ip;
        this.userName = userName;
        this.userPwd = userPwd;
    }

    public RemoteExecuteCommand() {

    }

    /**
     * 远程登录linux的主机
     *
     * @return 登录成功返回true，否则返回false
     * @author Ickes
     * @since V0.1
     */
    public Boolean login() {
        boolean flg = false;
        try {
            conn = new Connection(ip);
            conn.connect();//连接
            flg = conn.authenticateWithPassword(userName, userPwd);//认证
            if (flg) {
                System.out.println("认证成功！");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return flg;
    }

    /**
     * @param cmd 即将执行的命令
     * @return 命令执行完后返回的结果值
     * @author Ickes
     * 远程执行shll脚本或者命令
     * @since V0.1
     */
    public String execute(String cmd) {
        String result = "";
        try {
            if (login()) {
                Session session = conn.openSession();//打开一个会话
                session.execCommand(cmd);//执行命令
                result = processStdout(session.getStdout(), DEFAULTCHART);
                //如果为得到标准输出为空，说明脚本执行出错了
                if (StringUtils.isBlank(result)) {
                    result = processStdout(session.getStderr(), DEFAULTCHART);
                }
                conn.close();
                session.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }


    /**
     * @param cmd 即将执行的命令
     * @return 命令执行成功后返回的结果值，如果命令执行失败，返回空字符串，不是null
     * @author Ickes
     * 远程执行shll脚本或者命令
     * @since V0.1
     */
    public String executeSuccess(String cmd) {
        String result = "";
        try {
            if (login()) {
                Session session = conn.openSession();//打开一个会话
                session.execCommand(cmd);//执行命令
                result = processStdout(session.getStdout(), DEFAULTCHART);
                conn.close();
                session.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 解析脚本执行返回的结果集
     *
     * @param in      输入流对象
     * @param charset 编码
     * @return 以纯文本的格式返回
     * @author Ickes
     * @since V0.1
     */
    public static String processStdout(InputStream in, String charset) {
        InputStream stdout = new StreamGobbler(in);
        StringBuffer buffer = new StringBuffer();
        ;
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(stdout, charset));
            String line = null;
            while ((line = br.readLine()) != null) {
//                buffer.append(line+"\n");//按行输出
                buffer.append(line);//一行输出
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer.toString();
    }

    /**
     * 第一行不要。
     *
     * @param in
     * @param charset
     * @return
     */
    public static String processStdoutExceptLineOne(InputStream in, String charset) {
        InputStream stdout = new StreamGobbler(in);
        StringBuffer buffer = new StringBuffer();
        ;
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(stdout, charset));
            String line = null;
            int i = 0;
            while ((line = br.readLine()) != null) {
//                buffer.append(line+"\n");//按行输出
                if (i == 0) {
                    i++;
                } else {
                    buffer.append(line + "\n");//一行输出
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return buffer.toString();
    }

    public static void main(String[] args) {
//        RemoteExecuteCommand rec=new RemoteExecuteCommand("139.196.48.196", "root","Lczy2016cfq");
        RemoteExecuteCommand rec = new RemoteExecuteCommand("218.193.113.149", "ubuntu", "123");
        //执行命令
        try {
            if (rec.login()) {

                System.out.println("=====第一个步骤=====");
                Session session = conn.openSession();//打开一个会话
                //TODO:多条命令
                session.execCommand("cd /home/ubuntu/Desktop/music_rec/user_sim;echo \"123\" | sudo  -S ./caculate_tim_sim.sh similar");//执行命令
                String result = processStdout(session.getStdout(), DEFAULTCHART);
                //如果为得到标准输出为空，说明脚本执行出错了
                if (StringUtils.isBlank(result)) {
                    System.out.println("脚本出错");
                    result = processStdout(session.getStderr(), DEFAULTCHART);
                }
                System.out.println(result);
                session.close();

                System.out.println("=====第二个步骤=====");
                Session session2 = conn.openSession();//打开一个会话
                //TODO:多条命令
                session2.execCommand("cd /home/ubuntu/Desktop/music_rec/user_sim/result;cat xyy_result_m10d.json");//执行命令
                String result2 = processStdout(session2.getStdout(), DEFAULTCHART);
                //如果为得到标准输出为空，说明脚本执行出错了
                if (StringUtils.isBlank(result2)) {
                    System.out.println("脚本出错");
                    result2 = processStdout(session2.getStderr(), DEFAULTCHART);
                }
                System.out.println(result2);
                session2.close();

                System.out.println("=====第三个步骤=====");
                Session session3 = conn.openSession();//打开一个会话
                //TODO:多条命令
                session3.execCommand("cd /home/ubuntu/Desktop/music_rec/effective_range_of_singing_voice;python batch.py");//执行命令
//                session2.execCommand("cd /home/ubuntu/Desktop/music_rec/user_sim/result;ls");//执行命令
                String result3 = processStdout(session3.getStdout(), DEFAULTCHART);
                //如果为得到标准输出为空，说明脚本执行出错了
                if (StringUtils.isBlank(result3)) {
                    System.out.println("脚本出错");
                    result3 = processStdout(session3.getStderr(), DEFAULTCHART);
                }
                System.out.println(result3);
                session3.close();

                System.out.println("=====第四个步骤=====");
                Session session4 = conn.openSession();//打开一个会话
                //TODO:多条命令
                session4.execCommand("cd /home/ubuntu/Desktop/music_rec/recommendation;python recomendation.py");//执行命令
                String result4 = processStdout(session4.getStdout(), DEFAULTCHART);
                //如果为得到标准输出为空，说明脚本执行出错了
                if (StringUtils.isBlank(result4)) {
                    System.out.println("脚本出错");
                    result4 = processStdout(session4.getStderr(), DEFAULTCHART);
                }
                System.out.println(result4);
                session4.close();

                conn.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void setCharset(String charset) {
        DEFAULTCHART = charset;
    }

    public Connection getConn() {
        return conn;
    }

    public void setConn(Connection conn) {
        this.conn = conn;
    }

    public String getIp() {
        return ip;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getUserPwd() {
        return userPwd;
    }

    public void setUserPwd(String userPwd) {
        this.userPwd = userPwd;
    }
}
